package com.one.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.bo.EvaluationBo;
import com.one.bo.IndicatorBo;
import com.one.dto.*;
import com.one.entity.*;
import com.one.enums.*;
import com.one.mapper.*;
import com.one.service.StudentSemesterTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.one.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2021-10-11
 */
@Service
public class StudentSemesterTeacherServiceImpl extends ServiceImpl<StudentSemesterTeacherMapper, StudentSemesterTeacherEntity> implements StudentSemesterTeacherService {
    private final StudentSemesterTeacherMapper studentSemesterTeacherMapper;
    private final UserRoleMapper userRoleMapper;
    private final SemesterTeacherMapper semesterTeacherMapper;
    private final IndicatorResultInfoMapper indicatorResultInfoMapper;
    private final IndicatorInfoMapper indicatorInfoMapper;
    private final IndicatorOptionsMapper indicatorOptionsMapper;
    private final EvaluateResultInfoMapper evaluateResultInfoMapper;

    public StudentSemesterTeacherServiceImpl(EvaluateResultInfoMapper evaluateResultInfoMapper,IndicatorResultInfoMapper indicatorResultInfoMapper,IndicatorOptionsMapper indicatorOptionsMapper,StudentSemesterTeacherMapper studentSemesterTeacherMapper,UserRoleMapper userRoleMapper,SemesterTeacherMapper semesterTeacherMapper,IndicatorInfoMapper indicatorInfoMapper) {
        this.studentSemesterTeacherMapper = studentSemesterTeacherMapper;
        this.userRoleMapper = userRoleMapper;
        this.semesterTeacherMapper = semesterTeacherMapper;
        this.indicatorInfoMapper = indicatorInfoMapper;
        this.indicatorOptionsMapper = indicatorOptionsMapper;
        this.indicatorResultInfoMapper = indicatorResultInfoMapper;
        this.evaluateResultInfoMapper = evaluateResultInfoMapper;
    }
    @Override
    public Result selectEvaluation(EvaluationBo evaluationBo,String userID) {

        //数据校验
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(evaluationBo.getNumber(), evaluationBo.getPage()), "分页参数错误!");
        int page = evaluationBo.getPage();
        evaluationBo.setPage(PaginationUtils.getPageIndex(evaluationBo.getPage(), evaluationBo.getNumber()));
        //查询项目组评分 mybatis
        List<Object> result = null;
        QueryWrapper<UserRoleEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(UserRoleEntity::getUserId,userID).eq(UserRoleEntity::getRoleId, RoleEnum.STUDENT.getKey());
        UserRoleEntity userRoleEntity = userRoleMapper.selectOne(sectionQueryWrapper);
        evaluationBo.setUserId(userID);
        if (userRoleEntity != null) {
            result = studentSemesterTeacherMapper.selectEvaluation(evaluationBo);
            int sum = ((List<Integer>) result.get(1)).get(0);
            //记录总数为0
            if (sum == 0) return Result.error().message("查询结果为空");
            PaginationDate paginationDate = PaginationUtils.getPaginationDate(evaluationBo.getNumber(), page, sum);
            //当前页大于总页数
            if (PaginationUtils.isValid(paginationDate))
                return Result.error().message("分页参数错误!");
            List<StudentSemesterTeacherEntity> roleIndicatorViewEntities =  (List<StudentSemesterTeacherEntity>) result.get(0);
            return Result.ok().data(new ReturnDate(paginationDate,roleIndicatorViewEntities ));
        }else {
            result = semesterTeacherMapper.selectEvaluation(evaluationBo);
            int sum = ((List<Integer>) result.get(1)).get(0);
            //记录总数为0
            if (sum == 0) return Result.error().message("查询结果为空");
            PaginationDate paginationDate = PaginationUtils.getPaginationDate(evaluationBo.getNumber(), page, sum);
            //当前页大于总页数
            if (PaginationUtils.isValid(paginationDate))
                return Result.error().message("分页参数错误!");
            List<SemesterTeacherEntity> roleIndicatorViewEntities =  (List<SemesterTeacherEntity>) result.get(0);
            return Result.ok().data(new ReturnDate(paginationDate,roleIndicatorViewEntities));
        }
    }
    public Result selectIndicatorOptions(IndicatorBo indicatorBo) {
        QueryWrapper<IndicatorOptionsEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(IndicatorOptionsEntity::getIndCode, indicatorBo.getId()).eq(IndicatorOptionsEntity::getIsDeleted, IsDeletedEnum.NO.getKey()).orderByAsc(IndicatorOptionsEntity::getSort);
        List<IndicatorOptionsEntity> indicatorOptionsEntities = indicatorOptionsMapper.selectList(sectionQueryWrapper);
        if (indicatorOptionsEntities.size() == 0) {
            return Result.error().message("查询结果为空");
        }
        return Result.ok().data(indicatorOptionsEntities);
    }
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public Result teachaerEvaluation(EvaluationBo evaluationBo, String userID) {
        SelectIndicator selectIndicator = new SelectIndicator();
        selectIndicator.setId(evaluationBo.getIid());
        //查询指标 mybatis
        List<IndicatorInfo> result = indicatorInfoMapper.selectIndicator(selectIndicator);
        if (result.size() == 0) return Result.error().message("未找到指标");
        if(result.size()==1){
            selectIndicator.setId(null);
            selectIndicator.setName(null);
            selectIndicator.setParentIds(result.get(0).getParentIds());
            selectIndicator.setParentId(result.get(0).getId());
            result = indicatorInfoMapper.selectIndicator(selectIndicator);
        }
        for(IndicatorInfo indicatorInfo:result){
            if(indicatorInfo.getIsLeafNode().equals(IsLeafNode.YES.getKey())){
                IndicatorBo indicatorBo1 =  new IndicatorBo();
                indicatorBo1.setId(indicatorInfo.getId());
                indicatorInfo.setOptions((List<IndicatorOptionsEntity>) selectIndicatorOptions(indicatorBo1).getData());
            }
        }
        List<IndicatorInfo>  questionnaires= TreeUtils.createIndicatorTree(result,"0",100);
        //选项转换
        boolean[] options = DataUtils.getEvaluationOptions(evaluationBo.getRadio());
        //算分
        IndicatorResultInfoEntity indicatorResultInfoEntity = new IndicatorResultInfoEntity();
        indicatorResultInfoEntity.setSemCode(evaluationBo.getSemCode());
        indicatorResultInfoEntity.setUserCode(userID);
        indicatorResultInfoEntity.setTeachCode(evaluationBo.getTeachCode());
        indicatorResultInfoEntity.setCourseCode(evaluationBo.getCourseId());
        indicatorResultInfoEntity.setIsDeleted(IsDeletedEnum.NO.getKey());
        indicatorResultInfoEntity.setCreateBy(userID);
        indicatorResultInfoEntity.setCreateTime(DateUtils.getCurrentTime());

        float score = addIndicatorResultInfo(questionnaires,indicatorResultInfoEntity,options);
        //保存结果
        EvaluateResultInfoEntity evaluateResultInfoEntity = new EvaluateResultInfoEntity();
        evaluateResultInfoEntity.setSemCode(evaluationBo.getSemCode());
        evaluateResultInfoEntity.setUserCode(userID);
        evaluateResultInfoEntity.setTeachCode(evaluationBo.getTeachCode());
        evaluateResultInfoEntity.setCourseCode(evaluationBo.getCourseId());
        evaluateResultInfoEntity.setIsDeleted(IsDeletedEnum.NO.getKey());
        evaluateResultInfoEntity.setCreateBy(userID);
        evaluateResultInfoEntity.setCreateTime(DateUtils.getCurrentTime());
        evaluateResultInfoEntity.setRootIndCode(evaluationBo.getIid());
        evaluateResultInfoEntity.setScore(score);
        //查询是否是学生
        QueryWrapper<UserRoleEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(UserRoleEntity::getUserId,userID).eq(UserRoleEntity::getRoleId, RoleEnum.STUDENT.getKey());
        UserRoleEntity userRoleEntity = userRoleMapper.selectOne(sectionQueryWrapper);
        if(userRoleEntity==null){
            if(userID.equals(evaluationBo.getTeachCode())){
                evaluateResultInfoEntity.setEvalType(EvalType.Me.getKey());
            }else {
                evaluateResultInfoEntity.setEvalType(EvalType.TEACHER.getKey());
            }
        }else {
            evaluateResultInfoEntity.setEvalType(EvalType.STUDENT.getKey());
        }
        evaluateResultInfoMapper.insert(evaluateResultInfoEntity);
        return Result.ok();
    }

    @Override
    public Result getEvaluationLog(EvaluationBo evaluationBo) {
        //数据校验
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(evaluationBo.getNumber(), evaluationBo.getPage()), "分页参数错误!");
        int page = evaluationBo.getPage();
        evaluationBo.setPage(PaginationUtils.getPageIndex(evaluationBo.getPage(), evaluationBo.getNumber()));
        //查询项目组评分 mybatis
        List<Object> result = evaluateResultInfoMapper.getEvaluationLog(evaluationBo);
        int sum = ((List<Integer>) result.get(1)).get(0);
        //记录总数为0
        if (sum == 0) return Result.error().message("查询结果为空");
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(evaluationBo.getNumber(), page, sum);
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error().message("分页参数错误!");
        List<EvaluateResultInfoEntity> evaluateResultInfoEntities =  (List<EvaluateResultInfoEntity>) result.get(0);
        for (EvaluateResultInfoEntity evaluateResultInfoEntity:evaluateResultInfoEntities){
            evaluateResultInfoEntity.setEvalType(EvalType.getEnumValue(evaluateResultInfoEntity.getEvalType()));
        }
        return Result.ok().data(new ReturnDate(paginationDate,evaluateResultInfoEntities ));
    }

    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public float addIndicatorResultInfo(List<IndicatorInfo>  questionnaires,IndicatorResultInfoEntity indicatorResultInfoEntity,boolean[] options){
        float score = 0;
        for(IndicatorInfo indicatorInfo:questionnaires){
            if(IsLeafNode.YES.getKey().equals(indicatorInfo.getIsLeafNode())){
               if(indicatorInfo.getOptions()!=null){
                   for(IndicatorOptionsEntity indicatorOptionsEntity:indicatorInfo.getOptions()){
                       if(options[Integer.parseInt(indicatorOptionsEntity.getId())]){
                           indicatorResultInfoEntity.setIndCode(indicatorInfo.getCode());
                           indicatorResultInfoEntity.setChooseOption(indicatorOptionsEntity.getId());
                           indicatorResultInfoEntity.setWeight(indicatorOptionsEntity.getWeight());
                           score = score + indicatorOptionsEntity.getWeight() * indicatorInfo.getWeight();
                           indicatorResultInfoMapper.insert(indicatorResultInfoEntity);
                           break;
                       }
                   }
               }
            }else if(indicatorInfo.getChildren()!=null){
                score = score + addIndicatorResultInfo(indicatorInfo.getChildren(),indicatorResultInfoEntity,options)*indicatorInfo.getWeight();
            }
        }
        return score;
    }
}
